package com.king.distributedSession.jetty;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectionWatcher implements Watcher {

	private Logger log = LoggerFactory.getLogger(getClass());

	private static final int SESSION_TIMEOUT = 5000;

	private CountDownLatch signal = new CountDownLatch(1);

	/**
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public ZooKeeper connection(String servers) {
		ZooKeeper zk;
		try {
			zk = new ZooKeeper(servers, SESSION_TIMEOUT, this);
			signal.await();
			return zk;
		} catch (IOException e) {
			log.error("", e);
		} catch (InterruptedException e) {
			log.error("", e);
		}
		return null;
	}

	public void process(WatchedEvent event) {
		Event.KeeperState state = event.getState();
		if (state == Event.KeeperState.SyncConnected) {
			signal.countDown();
		}
	}
}